package com.chongchong.common.tool;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Set;

/**
 * @Author:tlp
 * @Date:2022-09-01 10:07
 * @Desc: 发送邮件工具类
 */

@Component
@Slf4j
public class EmailCommonUtil {

	@Value("${spring.mail.from:}")
	private String emailFrom;

	@Autowired(required = false)
	private JavaMailSender mailSender;

	/**
	 * @return java.lang.Boolean
	 * @date 2022/9/8 15:56
	 * @param    emailSet 邮箱地址集合
	 * @param    theme  邮件主题
	 * @param    title  邮件标题
	 * @param    content 邮件内容
	 */
	public Boolean sendMail(List<String> emailSet, String theme, String title, String content) {

        log.info(">>>>>>开始发送邮件：{}", emailSet);
		for (String email : emailSet) {

			// make mail
			try {
				log.info(">>>>>>发送邮件：{}", email);
				MimeMessage mimeMessage = mailSender.createMimeMessage();

				MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
				helper.setFrom(emailFrom);
				helper.setSubject(theme);
				helper.setTo(email);
				helper.setSubject(title);
				helper.setText(content, true);
				mailSender.send(mimeMessage);
				log.info(">>>>>>发送邮件成功：{}", email);
			} catch (Exception e) {
				e.printStackTrace();
				log.error(">>>>>>>>>>> send email fail , send error,{} ", e.getMessage());
			}
		}
		log.info(">>>>>>发送邮件结束");

		return true;
	}
}
